<!doctype html>
<html>

  <head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <link href="css/mui.min.css" rel="stylesheet" />
    <style type="text/css">
    	html,body,.mui-content{
    		height: 100%;
    		width: 100%;
    		background-color: #FFFFFF;
    	}
    	.logo-img{
    		width:100%;
    	}
    	.logo-img03{
    		width: 24.4%;
    		position:absolute;
    		top:40%;
    		left:38%
    	}
    	.logoin-title{
    		text-align: center;
    		font-size: 20px;
    		color: #FD7673;
    	}
    	/**/
    	.mui-input-group:before{
    		height: 0;
    	}
    	.mui-input-group:after{
    		height: 0;
    	}
      .area {
        margin: 20px auto 0px auto;
      }
      
      .mui-input-group {
        margin-top: 30px;
      }
      
      .mui-input-group:first-child {
        margin-top: 20px;
      }
      
      .mui-input-group label {
        width: 22%;
      }
      
      .mui-input-row label~input,
      .mui-input-row label~select,
      .mui-input-row label~textarea {
        width: 78%;
      }
      
      .mui-checkbox input[type=checkbox],
      .mui-radio input[type=radio] {
        top: 6px;
      }
      
  
      .mui-btn {
        padding: 10px;
      }
      
      .link-area {
        display: block;
        margin-top: 25px;
        text-align: center;
      }
      
      .spliter {
        color: #bbb;
        padding: 0px 8px;
      }
      

      .mui-content-padded, .check-update{
        width: 70%;
        margin: 25px auto 0;
        text-align: center;
      }
      .check-btn{
      	color:RGB(253,118,115);
      	border: 1px solid RGB(253,118,115);
      }
      #login{
      	color:white;
      	background-color: RGB(253,118,115);
      	border: 1px solid RGB(253,118,115);
      }
      .footerDiv{
      	margin: 80px auto 0;
      	width: 100%;
      }
      .name-vison{
      	text-align: center;
      	margin: 0;
      	padding: 0;
      	color:RGB(253,118,115);
      }
    </style>
    <script src="js/mui.min.js"></script>
    <script type="text/javascript">
      mui.init();
    </script>
  </head>

  <body>
    <div class="mui-content">
    	<div class="logo-header" style='position:relative'>
    		<img class="logo-img" src="./images/logoin.png" alt="" />
    		<img src="./images/logo_03.png" class='logo-img03' alt="" />
    		<p class="logoin-title">店内经营管理系统</p>
    	</div>
      <form id='login-form' class="mui-input-group">
        <div class="mui-input-row">
          <label>账号</label>
          <input id='account' type="text" class="mui-input-clear mui-input" placeholder="请输入账号">
        </div>
        <div class="mui-input-row">
          <label>密码</label>
          <input id='password' type="password" class="mui-input-clear mui-input" placeholder="请输入密码">
        </div>
      </form>
      <!--<form class="mui-input-group">
				<ul class="mui-table-view mui-table-view-chevron">
					<li class="mui-table-view-cell">
						自动登录
						<div id="autoLogin" class="mui-switch">
							<div class="mui-switch-handle"></div>
						</div>
					</li>
				</ul>
			</form>-->
      <div class="mui-content-padded">
        <button id='login' data-loading-text="登录中" class="mui-btn mui-btn-block ">登录</button>
      </div>
      <div class="check-update">
      	<!--<a  class="check-btn"></a>-->
      	<button class='check-btn mui-btn mui-btn-block'   >检查更新</button>
      </div>
      <div class='footerDiv'>
      	<p class="name-vison">商户：<span class="wareName"></span></p>
      	<p class="name-vison">版本号：<span class="vision"></span></p>
      </div>
      
    </div>

    </div>
    <script src="config.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
      var originData = {
        shops: [],
        userName: '',
        currentShop: ''
      };
      var isSubmit = false;
      var form = {
        logName: '',
        password: ''
      };
      var wgtVer = ''  //当前版本
      var downWgtWait
      var newVersion = '', //新版本
      downUrl=''  //下载地址
      mui.plusReady(function() {
        bindEvent();
        checkUpdate()
        getStoreList()
        document.querySelector('.wareName').innerText=config.wareName
      });
      //检查更新
      function checkUpdate(type) {
        plus.runtime.getProperty(plus.runtime.appid, function(inf) {
          wgtVer = inf.version;
          document.querySelector('.vision').innerText = wgtVer
        });
        config.ajax({
          url: config.basePath + '/app/checkLastByVersion',
          type: 'GET',
          success: function(res) {
            if(res.result === 1) {
            	newVersion = res.version.version
              if(res.version.version !== wgtVer) {
              	downUrl = config.imgPath + res.version.path
                ifDown()
              } else {
              	if(type) {
              		mui.toast('当前已是最新版本！')
              	}
              }
            }
          }
        })
      }
      //是否下载
      function ifDown() {
      	var btnArray = ['否', '是'];
      	mui.confirm('当前版本：'+wgtVer+'\n最新版本：'+newVersion, '更新', btnArray, function(e) {
      		if(e.index == 1) { 
      				downWgt(downUrl)
      		}
      	})
      }
      //下载更新
      function downWgt(wgtUrl) {
        downWgtWait = plus.nativeUI.showWaiting("下载更新文件...");
        var dtask = plus.downloader.createDownload(wgtUrl, {
          filename: "_doc/update/"
        }, function(d, status) {
          if(status == 200) {
            installWgt(d.filename); // 安装包
          } else {
            plus.nativeUI.alert("下载更新失败！");
          }
          plus.nativeUI.closeWaiting();
        });
        dtask.addEventListener('statechanged', onStateChanged, false)
        dtask.start()
      }
      //监听下载进度
      function onStateChanged(task, status) {
        if(status != null && status == 200 && task.state != null) {
          var a = task.downloadedSize / task.totalSize * 100;
          downWgtWait.setTitle("下载更新文件..." + parseInt(a) + "%");
        }
      }
      //安装更新
      function installWgt(path) {
        plus.nativeUI.showWaiting("安装更新文件...");
        plus.runtime.install(path, {}, function() {
          plus.nativeUI.closeWaiting();
          plus.nativeUI.alert("应用资源更新完成！", function() {
            plus.runtime.restart();
          });
        }, function(e) {
          plus.nativeUI.closeWaiting();
          console.log("安装更新文件失败[" + e.code + "]：" + e.message);
          plus.nativeUI.alert("安装更新文件失败[" + e.code + "]：" + e.message);
        });
      }
      // 获取所有门店列表
      function getStoreList() {
        var vm = this
        config.ajax({
          url: config.basePath + '/shops',
          headers: {
            'Content-Type': 'application/json'
          },
          crossDomain: true,
          dataType: 'json',
          type: 'GET',
          success: function(res) {
            if(res.result === 1) {
              originData.allShops = res.merchantStoreList
            }
          }
        });
      }

      function bindEvent() {
        mui('.mui-content-padded').on('tap', '#login', function() {
          mui('#account')[0].blur();
          mui('#password')[0].blur();
          getFormValue();
          var validateName = validateInput(form.logName, {
            required: true
          }, '请输入用户名!');
          var validatePassword = validateInput(form.password, {
            required: true
          }, '请输入密码!');
          if(validateName && validatePassword) {
            loginIn();
          }
        });

        mui.back = function() {
          var btnArray = ['是', '否'];
          mui.confirm('你确定退出应用？', '退出', btnArray, function(e) {
            if(e.index == 0) {
              plus.runtime.quit();
            } else {}
          });
        }
        mui('.check-btn')[0].addEventListener('tap',function(){
        	checkUpdate(1)
        })
      }

      function loginIn() {
        if(isSubmit) {
          return;
        }
        mui('#login').button('loading');
        isSubmit = true;
        console.log(111)
        config.ajax({
          url: config.basePath + '/login/doLogin',
          headers: {
            'Content-Type': 'application/json'
          },
          crossDomain: true,
          dataType: 'json',
          type: 'POST',
          data: form,
          success: function(res) {
          	console.log(JSON.stringify(res))
            if(res.result === 1) {
              originData.shops = res.info.shops;
              originData.pages = res.info.phonePages
              originData.userName = res.info.info.userName;
              originData.currentShop = res.info.currentShop;
              plus.nativeUI.toast('登陆成功');
              LoginSuccess();
              isSubmit = false;
            } else {
              isSubmit = false;
              mui.toast(res.errormsg);
            }
            setTimeout(function() {
              mui('#login').button('reset');
            }, 0)
          },
          error:function() {
          	mui.toast('登陆超时！')
          	mui('#login').button('reset');
          }
        });
        setTimeout(function(){
        	if(originData.shops===[]) {
        		isSubmit = false;
        		plus.nativeUI.toast('登陆超时，请重新登录');
        	}
        },5000)
      }

      function getFormValue() {
        form.logName = mui('#account')[0].value;
        form.password = mui('#password')[0].value;
      }

      function validateInput(val, rules, message) {
        if(rules.required === true && val === '') {
          plus.nativeUI.toast(message);
          return false;
        }
        return true;
      }

      function LoginSuccess() {
        originData.shopObjs = []
        if(localStorage.getItem('selectShop')) {
          for(var i = 0; i < originData.shops.length; i++) {
            for(var j = 0; j < originData.allShops.length; j++) {
              if(originData.shops[i] === originData.allShops[j].storeId) {
                originData.shopObjs.push(originData.allShops[j]);
              }
            }
          }
          mui.openWindow({
            url: 'switch/switch.html',
            id: 'switch-link',
            styles: {
              titleNView: {
                titleText: '切换门店',
                titleColor: "#FFFFFF",
                titleSize: "17px",
                backgroundColor: "#FF6800",
                autoBackButton: true,
                splitLine: {
                  color: "#CCCCCC",
                  height: "1px"
                }
              }
            },
            extras: {
              originData: originData
            }
          });
        } else {
          mui.openWindow({
            url: 'index.html',
            id: 'index',
            extras: {
              originData: originData
            }
          });
        }

      }
    </script>
  </body>

</html>